package com.hongli.blog.config;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** cookie
 * @Author ZERO
 * @Date 2021/11/11 15:38
 **/
public class CookieUtils {

    /** 获取cookie
      * @author ZERO
      * @date 2021/11/11 15:40
    **/
    public static String getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /** 添加cookie
      * @author ZERO
      * @date 2021/11/11 15:40
    **/
    public static void writeCookie(HttpServletResponse response, String cookieName, String value) {
        Cookie cookie = new Cookie(cookieName, value);
        cookie.setPath("/");
        cookie.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie);
    }

    /** 销毁cookies
      * @author ZERO
      * @date 2021/11/11 17:56
    **/
    public static void destroyCookies(HttpServletResponse response, String cookieName){
        Cookie cookie = new Cookie(cookieName, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
